<?php

namespace App\Http\Controllers;


use App\Model\Prize;
use App\Model\Info;
use App\Model\Province;
use App\Model\Record;
use App\User;
use Illuminate\Support\Facades\Log;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Redis;

class IndexController extends Controller
{

    const Time = array(
        '1' => '无需求',
        '2' => '三个月内',
        '3' => '半年内',
        '4' => '一年内'
    );
    const modles = array(
        '004020' => '全新致炫',
        '004021' => '致享',
        '004001' => '凯美瑞',
        '004002' => '汉兰达',
        '004013' => '致炫',
        '004014' => '雷凌',
        '004019' => '雷凌双擎',
        '004015' => '凯美瑞双擎',
    );

    const prize1 = array(
        '1' => array("name" => '1000元交强险基金', 'path' => 'timg.png', 'way' => '3月15日-4月30日内前往广汽丰田销售店购买雷凌Turbo，并在店内投保交强险，购车发票和交强险发票日期须在3月15日-5月10日期间，即可获得价值1000元加油卡，4月30日-5月31日奖品分批发放'),
        '3' => array("name" => '50元京东E卡', 'path' => 'timg4.png', 'way' => '即刻留下资料获取"到店核销码"，请于即日起14日内，前往广汽丰田销售店，到店免费试驾雷凌Turbo，核销后，京东E卡券码将于15个工作日内通过短信形式发送到您的手机'),
        '5' => array("name" => '599元户外帐篷', 'path' => 'timg5.png', 'way' => '即刻留下资料获取"到店核销码"，请于3月25日起14日内，前往广汽丰田销售店，到店免费试驾致享，核销后，我方将于5月4日统一安排礼品寄出'),
        '2' => array("name" => '149元小米手环2', 'path' => 'timg2.png', 'way' => '即刻留下资料获取"到店核销码"，请于即日起14日内，前往广汽丰田销售店，到店免费试驾雷凌Turbo，核销后，我方将于5月4日统一安排礼品寄出'),
        '4' => array("name" => '2888元ipad mini4', 'path' => 'timg3.png', 'way' => '即刻留下资料获取"到店核销码"，请于3月25日起14日内，前往广汽丰田销售店，到店试驾致享，核销后，我方将于5月4日统一安排礼品寄出'),
    );
    const prize2 = array(
        '1' => array("name" => '1000元交强险基金', 'path' => 'timg.png', 'way' => '3月15日-4月30日内前往广汽丰田销售店购买雷凌Turbo，并在店内投保交强险，购车发票和交强险发票日期须在3月15日-5月10日期间，即可获得价值1000元加油卡，4月30日-5月31日奖品分批发放'),
        '3' => array("name" => '50元京东E卡', 'path' => 'timg4.png', 'way' => '即刻获取"到店核销码"，请于即日起14日内，前往广汽丰田销售店，到店免费试驾雷凌Turbo，核销后，京东E卡券码将于15个工作日内通过短信形式发送到您的手机'),
        '5' => array("name" => '599元户外帐篷', 'path' => 'timg5.png', 'way' => '即刻获取"到店核销码"，请于3月25日起14日内，前往广汽丰田销售店，到店免费试驾致享，核销后，我方将于5月4日统一安排礼品寄出'),
        '2' => array("name" => '149元小米手环2', 'path' => 'timg2.png', 'way' => '即刻获取"到店核销码"，请于即日起14日内，前往广汽丰田销售店，到店免费试驾雷凌Turbo，核销后，我方将于5月4日统一安排礼品寄出'),
        '4' => array("name" => '2888元ipad mini4', 'path' => 'timg3.png', 'way' => '即刻获取"到店核销码"，请于3月25日起14日内，前往广汽丰田销售店，到店试驾致享，核销后，我方将于5月4日统一安排礼品寄出'),
    );
    const prize3 = array(
        '1' => array("name" => '1000元交强险基金', 'path' => 'timg.png', 'way' => '即刻留下资料获取“到店核销码”，请于3月15日-4月30日内前往广汽丰田销售店购买雷凌Turbo，并在店内投保交强险，购车发票和交强险发票日期须在3月15日-5月10日期间，即可获得价值1000元加油卡，4月30日-5月31日奖品分批发放'),
        '3' => array("name" => '50元京东E卡', 'path' => 'timg4.png', 'way' => '填写完整资料并提交后，点击所获奖品对应“获取核销码”，即可以短信形式获取"到店核销码"。请于即日起14日内，前往广汽丰田销售店，到店免费试驾雷凌Turbo，核销后，京东E卡券码将于15个工作日内通过短信形式发送到您的手机'),
        '5' => array("name" => '599元户外帐篷', 'path' => 'timg5.png', 'way' => '填写完整资料并提交后，点击所获奖品对应“获取核销码”，即可以短信形式获取"到店核销码"。请于3月25日起14日内，前往广汽丰田销售店，到店免费试驾致享，核销后，我方将于5月4日统一安排礼品寄出'),
        '2' => array("name" => '149元小米手环2', 'path' => 'timg2.png', 'way' => '填写完整资料并提交后，点击所获奖品对应“获取核销码”，即可以短信形式获取"到店核销码"。请于即日起14日内，前往广汽丰田销售店，到店免费试驾雷凌Turbo，核销后，我方将于5月4日统一安排礼品寄出'),
        '4' => array("name" => '2888元ipad mini4', 'path' => 'timg3.png', 'way' => '填写完整资料并提交后，点击所获奖品对应“获取核销码”，即可以短信形式获取"到店核销码"。请于3月25日起14日内，前往广汽丰田销售店，到店试驾致享，核销后，我方将于5月4日统一安排礼品寄出'),
    );

    public $province ='[{"province_name":"\u9ed1\u9f99\u6c5f\u7701","province_code":"057001","status":"True"},{"province_name":"\u5409\u6797\u7701","province_code":"057002","status":"True"},{"province_name":"\u8fbd\u5b81\u7701","province_code":"057003","status":"True"},{"province_name":"\u5317\u4eac\u5e02","province_code":"058001","status":"True"},{"province_name":"\u6cb3\u5317\u7701","province_code":"058002","status":"True"},{"province_name":"\u5185\u8499\u53e4\u81ea\u6cbb\u533a","province_code":"058003","status":"True"},{"province_name":"\u5c71\u897f\u7701","province_code":"058004","status":"True"},{"province_name":"\u5929\u6d25\u5e02","province_code":"058005","status":"True"},{"province_name":"\u5e7f\u897f\u58ee\u65cf\u81ea\u6cbb\u533a","province_code":"059002","status":"True"},{"province_name":"\u6d77\u5357\u7701","province_code":"059003","status":"True"},{"province_name":"\u798f\u5efa\u7701","province_code":"060001","status":"True"},{"province_name":"\u5e7f\u4e1c\u7701","province_code":"060002","status":"True"},{"province_name":"\u6c5f\u897f\u7701","province_code":"060003","status":"True"},{"province_name":"\u7518\u8083\u7701","province_code":"061001","status":"True"},{"province_name":"\u8d35\u5dde\u7701","province_code":"061002","status":"True"},{"province_name":"\u5b81\u590f\u56de\u65cf\u81ea\u6cbb\u533a","province_code":"061003","status":"True"},{"province_name":"\u9752\u6d77\u7701","province_code":"061004","status":"True"},{"province_name":"\u9655\u897f\u7701","province_code":"061005","status":"True"},{"province_name":"\u56db\u5ddd\u7701","province_code":"061006","status":"True"},{"province_name":"\u897f\u85cf\u81ea\u6cbb\u533a","province_code":"061007","status":"True"},{"province_name":"\u65b0\u7586\u7ef4\u543e\u5c14\u81ea\u6cbb\u533a","province_code":"061008","status":"True"},{"province_name":"\u4e91\u5357\u7701","province_code":"061009","status":"True"},{"province_name":"\u91cd\u5e86\u5e02","province_code":"061010","status":"True"},{"province_name":"\u5b89\u5fbd\u7701","province_code":"062001","status":"True"},{"province_name":"\u6cb3\u5357\u7701","province_code":"062002","status":"True"},{"province_name":"\u6e56\u5317\u7701","province_code":"062003","status":"True"},{"province_name":"\u6e56\u5357\u7701","province_code":"062004","status":"True"},{"province_name":"\u5c71\u4e1c\u7701","province_code":"063001","status":"True"},{"province_name":"\u6c5f\u82cf\u7701","province_code":"064001","status":"True"},{"province_name":"\u4e0a\u6d77\u5e02","province_code":"064002","status":"True"},{"province_name":"\u6d59\u6c5f\u7701","province_code":"065001","status":"True"}]';

    public function __construct()
    {
//        $id = '2';
    }


    public function isMobile()
    {
        // 如果有HTTP_X_WAP_PROFILE则一定是移动设备
        if (isset ($_SERVER['HTTP_X_WAP_PROFILE'])) {
            return true;
        }
        // 如果via信息含有wap则一定是移动设备,部分服务商会屏蔽该信息
        if (isset ($_SERVER['HTTP_VIA'])) {
            // 找不到为flase,否则为true
            return stristr($_SERVER['HTTP_VIA'], "wap") ? true : false;
        }
        // 脑残法，判断手机发送的客户端标志,兼容性有待提高
        if (isset ($_SERVER['HTTP_USER_AGENT'])) {
            $clientkeywords = array('nokia',
                'sony',
                'ericsson',
                'mot',
                'samsung',
                'htc',
                'sgh',
                'lg',
                'sharp',
                'sie-',
                'philips',
                'panasonic',
                'alcatel',
                'lenovo',
                'iphone',
                'ipod',
                'blackberry',
                'meizu',
                'android',
                'netfront',
                'symbian',
                'ucweb',
                'windowsce',
                'palm',
                'operamini',
                'operamobi',
                'openwave',
                'nexusone',
                'cldc',
                'midp',
                'wap',
                'mobile'
            );
            // 从HTTP_USER_AGENT中查找手机浏览器的关键字
            if (preg_match("/(" . implode('|', $clientkeywords) . ")/i", strtolower($_SERVER['HTTP_USER_AGENT']))) {
                return true;
            }
        }
        // 协议法，因为有可能不准确，放到最后判断
        if (isset ($_SERVER['HTTP_ACCEPT'])) {
            // 如果只支持wml并且不支持html那一定是移动设备
            // 如果支持wml和html但是wml在html之前则是移动设备
            if ((strpos($_SERVER['HTTP_ACCEPT'], 'vnd.wap.wml') !== false) && (strpos($_SERVER['HTTP_ACCEPT'], 'text/html') === false || (strpos($_SERVER['HTTP_ACCEPT'], 'vnd.wap.wml') < strpos($_SERVER['HTTP_ACCEPT'], 'text/html')))) {
                return true;
            }
        }
        return false;
    }

    public function getRandChar($length){
        $str = null;
        $strPol = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789abcdefghijklmnopqrstuvwxyz";
        $max = strlen($strPol)-1;

        for($i=0;$i<$length;$i++){
            $str.=$strPol[rand(0,$max)];//rand($min,$max)生成介于min和max两个数之间的一个随机整数
        }

        return $str;
    }

    /**
     * 获取ip
     * 生成用户数据
     */
    public function userinfo()
    {
//        echo 1;
        $ip = $_SERVER['REMOTE_ADDR'];
//        $ipgroup=array(
//            '111.41.238.160',
//            '111.41.238.189',
//            '111.41.239.10',
//            '111.41.239.43',
//            '125.47.69.52',
//            '140.207.185.123',
//            '171.43.190.129',
//            '180.127.108.211',
//            '180.127.118.139',
//            '180.127.118.168',
//            '27.19.195.76',
//            '60.205.217.211',
//            '60.218.122.221',
//            '192.168.1.124'
//        );
//        if(in_array($ip,$ipgroup)){
//            die;
//        }
//        die;
//        $ip = $this->Getip();
//        $br = $this->GetBrowser();
//        $sys = $this->GetOs();
        if(!isset($_COOKIE["token"])){
            $token = $this->getRandChar(55);
            setcookie("token",$token,time()+3592000);
        }else{
            $token =$_COOKIE["token"];
        }

        $info = User::where(['token'=>$token])->first();
        if (!empty($info)) {
            $_SESSION["id"] = $info->id;
            return $info->id;
        } else {
            if($this->isMobile()){
                $type='1';
            }else{
                $type='2';
            }
            $id = User::insertGetId(['token'=>$token,'ip'=>$ip,'created_at'=>date("y-m-d H:i:s"),'type'=>$type]);
            $_SESSION["id"] = $id;
            return $id;
        }

    }

    /**
     * 活动首页
     */
    public function index(Request $request)
    {
        $time = date("Y-m-d");
        if(empty($request->test)){
            if( $time >='2017-05-01'){
                if ($this->isMobile()) {//手机
                    return view("show.end");
                }else{
                    return view("index.end");
                }
            }
        }
//        $id = $this->userinfo();
        if(isset($_SESSION["id"])){
            $id = $_SESSION["id"];
        }else{
            $id = $this->userinfo();
        }

        $status = User::check($id);
//        dump($this->isMobile()) ;
//        die;
        if ($this->isMobile()) {//手机
            $list = $this->prize('0', '1');
//            dd($list);
            $record = Record::where(['user_id' => $id, "win" => '1'])->count();//获奖信息
//        dd($list);
            return view("show.index", ['status' => $status,'list'=>$list,'win'=>$record]);
        } else {//电脑
            $count = Info::where("user_id", $id)->count();
            $province = json_decode($this->province);
//            $modles = DB::table("modles")->where("status", "True")->get();
            return view("index.index", ['status' => $status, 'time' => self::Time, 'nums' => $count, 'province' => $province, "modles" =>  self::modles]);
        }

    }

    /**
     * 获取奖品信息
     */

    public function getprize($proArr)
    {
        $result = '';

        //概率数组的总概率精度
        $proSum = array_sum($proArr);

        //概率数组循环
        foreach ($proArr as $key => $proCur) {
            $randNum = mt_rand(1, $proSum);
            if ($randNum <= $proCur) {
                $result = $key;
                break;
            } else {
                $proSum -= $proCur;
            }
        }
        unset ($proArr);

        return $result;

    }

    /**
     *
     */
    public function start($type = '')
    {

//        DB::listen(function ($sql){
//            dump($sql);
//        });
//        $this->userinfo();
//        $id = $_SESSION["id"];
        if(isset($_SESSION["id"])){
            $id = $_SESSION["id"];
        }else{
            $id = $this->userinfo();
        }
        $status = User::check($id);
        if (!$status) {
            echo json_encode(array('err' => '0', 'msg' => '抽奖次数已用完'));
        } else {

//            $prize_arr = Prize::get(["min_angle as min", "max_angle as max", 'id', "type", "proab as v"])->toarray();
//            dd($prize_arr);
            //奖项初始化
            $prize_arr = array(
                '0' => array('id' => 1, 'min' => 315, 'max' => 355, 'prize' => '1000元交强险基金', 'type'=>'雷凌购车礼','v' => 0),
                '1' => array('id' => 2, 'min' => 255, 'max' => 290, 'prize' => '149元小米手环2','type'=>'雷凌到店礼', 'v' => 0),
                '2' => array('id' => 3, 'min' => 190, 'max' => 235, 'prize' => '50元京东E卡', 'type'=>'雷凌到店礼','v' => 100),
                '3' => array('id' => 4, 'min' => 5, 'max' => 50, 'prize' => '2888元ipad mini4','type'=>'致享到店礼', 'v' => 0),
                '4' => array('id' => 5, 'min' => 130, 'max' => 170, 'prize' => '599元户外帐篷','type'=>'致享到店礼', 'v' => 0),
                '5' => array('id' => 6, 'min' =>75 , 'max' => 115, 'prize' => '没有中奖','type'=>'', 'v' => 0)
            );
//            dd($prize_arr,$prize_a);
            //查看当前时间 是否在活动期间

            if(date("H:i:s",time()) > '09:00:00' && date("H:i:s",time()) < '23:59:59'){

                //抽奖开始
                foreach ($prize_arr as $key => $val) {
                    $arr[$val['id']] = $val['v'];
                }
                $rid = $this->getprize($arr); //根据概率获取奖项id
                if($rid !='6'){
                    $check = Prize::check($rid);//判断当前奖品是否有限制数量
                    if ($check) {
                        $rch = Prize::check('3');//判断当前奖品是否有限制数量
                        if($rch){
                            $rid='6';
                        }else{
                            $rid='3';
                        }
                    }
                }
//                Log::info("时间内");
            }else{
                $rid='6';
//                Log::info("时间外");
            }
            $res = $prize_arr[$rid - 1]; //中奖项
            $min = $res['min'];
            $max = $res['max'];
            if ($res['id'] == 6) { //六等奖
//                $i = mt_rand(0, 5);
//                $result['angle'] = mt_rand($min[$i], $max[$i]);
                $result['angle'] = mt_rand($min, $max);
                Record::recode(array("win" => '0', 'user_id' => $id, 'pid' => $res['id'], 'created_at' => date("Y-m-d H:i:s"), 'date' => date("Y-m-d")));
            } else {

                User::increments(array("id" => $id), 'win_num');
                Record::recode(array("win" => '1', 'user_id' => $id, 'pid' => $res['id'], 'created_at' => date("Y-m-d  H:i:s"), 'date' => date("Y-m-d")));
                $result['angle'] = mt_rand($min, $max); //随机生成一个角度
            }
            User::decrements(array("id" => $id), 'nums');
            $result['type'] = $res['type'];
            $result['id'] = $res['id'];
            if (!empty($type) && $res['id'] != '6') {
//                $num = Info::check($id);//判断是第几次转
//                if($num){
                    $prize = self::prize2[$res['id']];
//                }else{
//                    $prize = self::prize1[$res['id']];
//                }
                $result["prize"] = $prize;
            }

            echo json_encode($result);
        }
    }

    /**
     * @return bool
     * 判断是不是微信浏览器
     */

    public function is_weixin()
    {
        if (strpos($_SERVER['HTTP_USER_AGENT'], 'MicroMessenger') !== false) {
            return true;
        }
        return false;
    }

    /**
     * 奖品详情页
     */
    public function detail()
    {
//        $this->userinfo();
//        $id = $_SESSION["id"];

        if(isset($_SESSION["id"])){
            $id = $_SESSION["id"];
        }else{
            $id = $this->userinfo();
        }
        $record = Record::where(['user_id' => $id, "win" => '1'])->first();//获奖信息
        if (!empty($record)) {
            $num = Info::check($id);//判断是第几次转
            if ($num == '1') {
                $prize = self::prize1;
            } else {
                $prize = self::prize2;
            }
            $weixin = $this->is_weixin();
//            dd( $prize[$record->pid]);
            return view("show.detail", ['prize' => $prize[$record->pid], 'id' => $record->pid, 'num' => $num, 'weixin' => $weixin, 'code' => $record->code]);
        } else {
            return redirect("/");
        }


    }

    /**
     * 填写资料
     */

    public function info(Request $request)
    {
//        $this->userinfo();
//        $id = $_SESSION["id"];

        if(isset($_SESSION["id"])){
            $id = $_SESSION["id"];
        }else{
            $id = $this->userinfo();
        }
        if ($request->isMethod("post")) {
            if(empty($request->name) ||empty($request->phone) ||empty($request->province)||empty($request->city)||empty($request->shop)||empty($request->type)|empty($request->time)){
                return redirect("/write/info");
            }
            //处理填写的信息
            $data = array(
                'name' => $request->name,
                'phone' => $request->phone,
                'province' => $request->province,
                'city' => $request->city,
                'shop' => $request->shop,
                'type' => $request->type,
                'time' => $request->time,
                'user_id' => $id,
                'created_at'=>date("Y-m-d H:i:s")
            );
            $status = Info::insert($data);
            if ($status) {
                $this->uploadinfo($data);
                if (empty($request->nums)) {//赠送一次机会  回首页继续玩
                    User::increments(array("id" => $id), 'nums');
                    return redirect("/");
                } else {//直接获取发送验证码
                   $record = Record::where(['user_id' => $id, "win" => '1'])->first();//获奖信息
                   $ret=$this->send($record->pid);
//                    $ret='1';
                    if( !empty($ret)){
                        $record->code = $ret;
                        $record->save();
                        Prize::where("id",$record->pid)->decrement('stock');
                    }else
                    {
                        $ret['code']='3';
                    }

                    return redirect("/getcode");
                }
            } else {
                Log::info(json_encode($data));
                return redirect("/");
            }
        } else {
            $count = Info::where("user_id", $id)->count();
            if (empty($count)) {
                $win = Prize::win($id);
                $province = json_decode($this->province);
//                $modles = DB::table("modles")->where("status", "True")->get();
                return view("show.info", ['time' => self::Time, 'nums' => $win, 'province' => $province, "modles" => self::modles]);
            } else {//已经存在用户信息  回到首页
                return redirect("/");
            }
        }
    }

    /**
     * 获取获奖者信息
     */

    public function prize($start = '', $type = "")
    {
        if (empty($start)) {
            $start = 0;
        }
        $list =  DB::table("barrage")->orderby("id", 'desc')
            ->skip(0)->take(20)->get(["phone", 'prize']);
        if (!empty($type)) {
            return $list;
        } else {
            echo json_encode($list);
        }
    }

    /**
     * 获得到店核销码
     */

    public function getcode()
    {
//        $this->userinfo();
//        $id=$_SESSION["id"];

        if(isset($_SESSION["id"])){
            $id = $_SESSION["id"];
        }else{
            $id = $this->userinfo();
        }
        $data = Record::where("user_id",$id)->where(['win'=>'1'])->first();
        if(!empty($data)){
//            $ret=0;//发送短信
            if($data->code == '0'){
                $ret = $this->send($data->pid);
//                $ret='2';
                if(!empty($ret)){
                    Prize::where("id",$data->pid)->decrement('stock');
                    $data->code=$ret;
                    $data->save();
                }
            }
            return view("show.getcode");
        }else{
            return redirect("/");
        }

    }

    /**
     * @param $code
     * 根据省份code 获取城市列表
     */

    public function city($code)
    {

        $list = DB::table("city")->where("city_code", 'like', $code . "%")->where("status", "True")->get(["city_name", "city_code"]);
        echo json_encode($list);

    }

    /**
     * @param $code
     * 根据城市code码获取 门店列表
     */
    public function shop($code)
    {
        $list = DB::table("shop")->where("dealer_city_code", $code)->get(["dealer_name", "dealer_code"]);
        echo json_encode($list);
    }

    /**
     * @param Request $request
     * 检查手机号有没有被注册
     */

    public function check_tel(Request $request)
    {
        $count = Info::where("phone", $request->phone)->count();
        if ($count) {
            echo json_encode(array("code" => '2'));
        } else {
            echo json_encode(array("code" => '1'));
        }
    }


    public function handle_info(Request $request)
    {
//        $this->userinfo();
//        $id = $_SESSION["id"];

        if(isset($_SESSION["id"])){
            $id = $_SESSION["id"];
        }else{
            $id = $this->userinfo();
        }
        $ret = array();
        if ($request->isMethod("post")) {
            //判断手机号是否已经写入
            $count = Info::where("phone", $request->phone)->count();
            if ($count) {
                $ret["code"] = '2';
            } else {
                $count = Info::where("user_id", $id)->count();
                if ($count) {
                    $ret["code"] = '5';
                } else {
                    //处理填写的信息
                    $data = array(
                        'name' => $request->name,
                        'phone' => $request->phone,
                        'province' => $request->province,
                        'city' => $request->city,
                        'shop' => $request->shop,
                        'type' => $request->type,
                        'time' => $request->time,
                        'user_id' => $id,
                        'created_at'=>date("Y-m-d H:i:s")
                    );

                    $status = Info::insert($data);
                    if ($status) {
                        $this->uploadinfo($data);
                        if (empty($request->nums)) {//赠送一次机会  回首页继续玩
                            User::increments(array("id" => $id), 'nums');
                            $ret["code"] = '1';
                        } else {//直接获取发送验证码
//                            $record = Record::where(['user_id' => $id, "win" => '1'])->first();//获奖信息
//                            $record->code = '1';
//                            $record->save();
                            $ret["code"] = '3';
                        }
                    }
                }
            }
        } else {
            $ret["code"] = '4';
        }
        echo json_encode($ret);

    }

    /**
     * 点击获取核销码
     */

    public function sendcode($prize){
//        $this->userinfo();
//        $id=$_SESSION["id"];

        if(isset($_SESSION["id"])){
            $id = $_SESSION["id"];
        }else{
            $id = $this->userinfo();
        }
        $ret=array('code'=>"");
        $info = Record::where(['user_id'=>$id,'win'=>'1','pid'=>$prize,'code'=>'0'])->first();

        if(count($info)){
            $rets = $this->send($prize);
            if( !empty($rets) && $rets!='500'){
                $info->code =$rets;
                $info->save();
                Prize::where("id",$prize)->decrement('stock');
                $ret['code']='1';
            }else{
                $ret['code']='3';
            }
        }else{//没有对应奖品
            $ret['code']='2';
        }

        echo json_encode($ret);

    }

    public function curlget($url)
    {
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($curl, CURLOPT_TIMEOUT, 500);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, TRUE);
        curl_setopt($curl, CURLOPT_USERAGENT, "");
        curl_setopt($curl, CURLOPT_URL, $url);
        $res = curl_exec($curl);
        curl_close($curl);
        return $res;
    }

    public function send($prize){
//        dd($_SESSION['id']);


//        $id=$_SESSION['id'];

        if(isset($_SESSION["id"])){
            $id = $_SESSION["id"];
        }else{
            $id = $this->userinfo();
        }
        $infos = Info::where('user_id',$id)->first();
        if(!empty($infos)){
//            dd($_SESSION["id"]);
            $pinfo =   Prize::where("id",$prize)->first();

            if($pinfo->stock <=0){
                return "";
            }else{


        //发送核销码
        if($prize=='1'){
            $redis = 'num_you';
            $hxcode = Redis::spop("code_you");
            $temp='SMS_62430279';
            $content = '【广丰商城丰云惠】尊敬的用户，恭喜您在“福利大轮盘”活动中，获得价值1000元油卡一张。核销码为：'.$hxcode.'，凭此码在3月15日-4月30日内到就近广汽丰田销售店，购买雷凌Turbo并在店内购买交强险，且购车发票日期需为3月15日至5月10日，方能成功兑换油卡，感谢您的参与。销售信息详询客服电话：400-830-8888转1';
        }
        if($prize=='2'){
            $redis = 'num_xiaomi';
            $hxcode = Redis::spop("code_xiaomi");
            $temp='SMS_62325407';
            $content = '【广丰商城丰云惠】尊敬的用户，恭喜您在“福利大轮盘”活动中，获得价值149元小米手环一支。核销码为：'.$hxcode.'，凭此码在即日起14日内到广汽丰田销售店进行核销，我方将于您到店核销后15个工作日内将奖品寄出，感谢您的参与。销售信息详询客服电话：400-830-8888转1';
        }
        if($prize=='3'){
            $redis = 'num_e';
            $hxcode = Redis::spop("code_e");
            $temp='SMS_62550275';
            $content = '【广丰商城丰云惠】尊敬的用户，恭喜您在“福利大轮盘”活动中，获得价值50元京东e卡一张。核销码为：'.$hxcode.'，凭此码在即日起14日内到广汽丰田销售店进行核销，京东e卡的卡券和密码将会在到店核销后15个工作日内以短信形式发出，感谢您的参与。销售信息详询客服电话：400-830-8888转1';
        }
        if($prize=='4'){
            $redis = 'num_ipad';
            $hxcode = Redis::spop("code_ipad");
            $temp='SMS_62475289';
            $content = '【广丰商城丰云惠】尊敬的用户，恭喜您在“福利大轮盘”活动中，获得价值2888元iPad mini 4一台。核销码为：'.$hxcode.'，凭此码在即日起14日内到广汽丰田销售店进行核销，我方将于您到店核销后15个工作日内将奖品寄出，感谢您的参与。销售信息详询客服电话：400-830-8888转1';
        }
        if($prize=='5'){
            $redis = 'num_tent';
            $hxcode = Redis::spop("code_tent");
            $temp='SMS_62485257';
            $content = '【广丰商城丰云惠】尊敬的用户，恭喜您在“福利大轮盘”活动中，获得价值599元户外帐篷一个。核销码为：'.$hxcode.'，凭此码在即日起14日内到广汽丰田销售店进行核销，我方将于您到店核销后15个工作日内将奖品寄出，感谢您的参与。销售信息详询客服电话：400-830-8888转1';
        }

        if($hxcode !=''){
            Log::info("给手机号为".$infos->phone.'的用户发送核销码，核销码是'.$hxcode);

//            $rets = $this->sendsms($hxcode,$infos->phone,$temp);


            $url='http://sdk4rptws.eucp.b2m.cn:8080/sdkproxy/sendsms.action?cdkey=6SDK-EMY-6688-KIZNL&password=020521&phone='.$infos->phone.'&message='.$content;

            $rets= $this->curlget($url);
//            $rets='0';
            if(intval($rets)==0){
                $p=array(
                    '1'=>'1000元交强险基金',
                    '2'=>'149元小米手环2',
                    '3'=>'50元京东E卡',
                    '4'=>'2888元ipad mini4',
                    '5'=>'599元户外帐篷'
                );
                Redis::incr($redis);
                DB::table("barrage")->insert(array('phone'=>$infos->phone,'code'=>$hxcode,'prize'=>$p[$prize],'time'=>date("Y-m-d H:i;s")));
                return $hxcode;
            }else{
                return "";
            }
        }else{
            return "";
        }
            }
        }else{
            return "500";
        }


//        $rets=0；


    }


    public  function  sendsms($code,$phone,$template){


        include public_path("/sms/TopSdk.php");
        date_default_timezone_set('Asia/Shanghai');

        $code = '{"code":"'.$code.'"}';

        $c = new \TopClient();
        $c ->appkey = '23757410' ;
        $c ->secretKey = "4dd822f6ae64faa9359495e8ba266b2f" ;
        $req = new \AlibabaAliqinFcSmsNumSendRequest;
        $req ->setExtend( "" );
        $req ->setSmsType( "normal" );
        $req ->setSmsFreeSignName( "广丰商城丰云惠" );
        $req->setSmsParam($code);
        $req ->setRecNum( $phone );
        $req ->setSmsTemplateCode( $template );
        $resp = $c ->execute( $req );

       return $resp->result;


    }

    /**
     * 上传数据
     */

    public function uploadinfo($data){
        $infos=array();
        if (preg_match("/[\x7f-\xff]/", $data["province"])) {
            $infos["province"]['code'] = Province::pro_code($data["province"]);
            $infos["province"]['name'] =$data["province"];
        }else{
            $infos["province"]['code'] =$data["province"];
            $infos["province"]['name'] = Province::pro_name($data["province"]);
        }
        if (preg_match("/[\x7f-\xff]/", $data["city"])) {
            $infos["city"]['code'] = Province::city_code($data["city"]);
            $infos["city"]['name']=$data["city"];
        }else{
            $infos["city"]['code']=$data["city"];
            $infos["city"]['name'] = Province::city_name($data["city"]);
        }
        if (preg_match("/[\x7f-\xff]/", $data["shop"])) {
            $infos["shop"]['code'] = Province::shop_code($data["shop"]);
        }else{
            $infos["shop"]['code']=$data["shop"];
        }
        if (preg_match("/[\x7f-\xff]/", $data["type"])) {
            $infos["modle"]['code'] = array_search($data["type"],self::modles);
            $infos["modle"]['name'] =$data["type"];
        }else{
            $infos["modle"]['code']=$data["type"];
            $infos["modle"]['name'] = self::modles[$data["type"]];
        }
//        dd($infos);
        $time=date("YmdHis").rand(1000,9999);
          $info = '[
    {
        "media_code": "91de4f09-9a2d-4b4e-9ed9-0a0318633859",
        "clue_code": "'.$time.'",
        "dealer_code": "'.$infos["shop"]['code'].'",
        "is_publicorder": 2,
        "clue_type": 1,
        "modle_code": "'.$infos["modle"]['code'].'",
        "modle_name": "'.$infos["modle"]['name'].'",
        "series_code": "",
        "series_name": "",
        "province_code": "'.$infos["province"]['code'].'",
        "province_name": "'.$infos["province"]['name'].'",
        "city_code": "'.$infos["city"]['code'].'",
        "city_name": "'.$infos["city"]['name'].'",
        "district_code": "",
        "district_name": "",
        "content": "",
        "create_time": "'.date("Y-m-d H:i:s").'",
        "status": 0,
        "customer_name": "'.$data["name"].'",
        "gender": "",
        "phone": "'.$data["phone"].'",
        "business_phone": "",
        "mobile": "",
        "email": "",
        "address": "",
        "contact_method": "",
        "fax": "",
        "buy_date": "'.$data["time"].'",
        "communication_time": "",
        "pre_fetch_time": "",
        "pre_payment_method": "",
        "arrangement": "",
        "pre_time": "",
        "promotion_price": "",
        "remark": "",
        "add": ""
    }
]';
        $url="http://gcloudintf.gac-toyota.com.cn:8002/GCloudWebService.asmx/SetSalesLeads";

        $arr="media_code=91de4f09-9a2d-4b4e-9ed9-0a0318633859&Interface_name=Interface_salesleads&jsonstring=".$info;

        $pro = $this->get_url_contents($url,$arr);

    }
    /**
     * curl post
     * @param type $url
     * @return json
     * @author wx
     */
    public function get_url_contents($url,$post_data=''){
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt ( $ch, CURLOPT_POST, 1 );
        // 把post的变量加上
        curl_setopt($ch, CURLOPT_POSTFIELDS, $post_data);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
//        curl_setopt($ch, CURLOPT_CUSTOMREQUEST, POST);
        curl_setopt($ch, CURLOPT_AUTOREFERER, 1);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);// 设为TRUE把curl_exec()结果转化为字符串，而不是直接输出
        $tmpInfo = curl_exec($ch);
        curl_close($ch);
        return json_decode($tmpInfo,true);
    }
//
//    public function sendsms(){
////        $infos = DB::table('record')
////            ->leftJoin('infos', 'record.user_id', '=', 'infos.user_id')
////            ->where(['record.pid'=>'1','record.win'=>'1'])
////            ->where('record.code', '!=', '0')
////            ->where('infos.phone', '!=', '')
////            ->select('phone', 'record.user_id')
////            ->get();
//        $infos = DB::table('phone')->select('phone')->get();
//        foreach($infos as $key => $val){
//            Log::info("给手机号为".$val->phone.'的用户发送兑换通知');
//            $content = '温馨提示：您之前在丰云惠商城“福利大转盘”抽中的价值1000元雷凌Turbo购车礼，请尽快在4月30日前凭核销码到广汽丰田授权销售店，购买雷凌Turbo并在店内投保交强险，购车发票需在3月15日至5月10日，即可兑换价值1000元的加油卡！超值福利，机不可失，客服热线：400-830-8888转1';
//            $url='http://sdk4rptws.eucp.b2m.cn:8080/sdkproxy/sendsms.action?cdkey=6SDK-EMY-6688-KIZNL&password=020521&phone='.$val->phone.'&message='.$content;
//            $rets= $this->curlget($url);
//        }
//
//    }
}
